package com.study.puppeteer.controller;

import com.ruiyun.jvppeteer.api.core.Browser;
import com.ruiyun.jvppeteer.api.core.JSHandle;
import com.ruiyun.jvppeteer.api.core.Page;
import com.ruiyun.jvppeteer.api.core.Response;
import com.ruiyun.jvppeteer.cdp.core.Puppeteer;
import com.ruiyun.jvppeteer.cdp.entities.GoToOptions;
import com.ruiyun.jvppeteer.cdp.entities.LaunchOptions;
import com.ruiyun.jvppeteer.cdp.entities.PDFOptions;
import com.ruiyun.jvppeteer.cdp.entities.PaperFormats;
import com.ruiyun.jvppeteer.common.PuppeteerLifeCycle;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Arrays;

@RestController
@RequestMapping("convert")
public class ConvertController {

    @RequestMapping("pdf")
    public ResponseEntity<byte[]> url(String url) throws Exception {
        Browser browser = null;
        Page page = null;
        try {
            browser = Puppeteer.launch(LaunchOptions.builder().headless(true).defaultViewport(null).args(Arrays.asList("--no-sandbox", "--disable-setuid-sandbox")).build());

            page = browser.newPage();
            GoToOptions goToOptions = new GoToOptions();
            goToOptions.setWaitUntil(Arrays.asList(PuppeteerLifeCycle.values()));
            page.goTo(url, goToOptions);
            JSHandle handle = page.evaluateHandle("() => document.title");
            String fileName = "out.pdf";
            if (handle != null && handle.remoteObject() != null) {
                fileName = handle.remoteObject().getValue() + ".pdf";
            }
            PDFOptions options = new PDFOptions();
            options.setFormat(PaperFormats.a4);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(fileName, Charset.defaultCharset()))
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(page.pdf(options));
        } finally {
            if (page != null) {
                page.close();
            }
            if (browser != null) {
                browser.close();
            }
        }
    }
}
